package com.zdlee.netty.server15.server.handler;

import com.zdlee.netty.server15.request.MessageRequestPacket;
import com.zdlee.netty.server15.response.MessageResponsePacket;
import com.zdlee.netty.server15.session.Session;
import com.zdlee.netty.server15.util.SessionUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;

/**
 * @author zdlee
 * @description: ${DESCRIPTION}
 * @create 2018-11-29 16:49
 */
public class MessageRequestHandler extends SimpleChannelInboundHandler<MessageRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageRequestPacket msg) throws Exception {
/*        MessageResponsePacket messageResponsePacket=new MessageResponsePacket();
        System.out.println(new Date() + ": 收到客户端消息: " + msg.getMessage());

        messageResponsePacket.setMessage("服务端回复【" + msg.getMessage() + "】");
        ctx.channel().writeAndFlush(msg);*/
        // 1.拿到消息发送方的会话信息
        Session session= SessionUtil.getSession(ctx.channel());

        // 2.通过消息发送方的会话信息构造要发送的消息
        MessageResponsePacket messageResponsePacket=new MessageResponsePacket();
        messageResponsePacket.setFromUserId(session.getUserId());
        messageResponsePacket.setFromUserName(session.getUserName());
        messageResponsePacket.setMessage(msg.getMessage());

        //3.拿到消息接收方的channel
        Channel toUserChannel=SessionUtil.getChannel(msg.getToUserId());
        //4.讲消息发送到消息接收方
        if(toUserChannel!=null && SessionUtil.hasLogin(toUserChannel))
        {
            toUserChannel.writeAndFlush(messageResponsePacket);
        }else
        {
            System.err.println("["+msg.getToUserId()+"]不在线,发送失败!");
        }

    }


}
